<template>
    <div class="address-container">
        <!-- 导航 -->
        <TmallNavBar>
            <template #left><i class="icon iconfont icon-zuojiantou"></i></template>
            <template #default>收货地址</template>
        </TmallNavBar>

        <!-- 骨架屏 -->
        <van-skeleton v-if="isShowSkeleton">
            <template #template>
                <div class="skeleton-address-list">
                    <div class="skeleton-address-item" v-for="(item) in 4" :key="item" >
                        <div>
                            <van-skeleton-paragraph class="skeleton-address-text" row-width="30%"/>
                            <van-skeleton-paragraph style="height: 2px;margin-bottom: 10px;"/>

                            <van-skeleton-paragraph class="skeleton-address-text" row-width="40%"/>
                            <van-skeleton-paragraph/>
                        </div>
                    </div>
                </div>
            </template>
        </van-skeleton>

        <!-- 收货地址列表 -->
        <div class="address-list" v-if="userDeliveryAddrList.length > 0">
            <van-swipe-cell
                v-for="(item, index) in userDeliveryAddrList"
                :key="index"
            >
                <van-cell-group style="margin: 5px 5px;">
                    <van-cell
                        size="large"
                        :title="item.name"
                    >
                        <template v-if="item.is_default == 1" #value>
                            <van-tag
                                mark
                                color="#27BA9B"
                                size="medium"
                                type="primary">默认</van-tag>
                        </template>
                    </van-cell>
                    <van-cell
                        @click="showEditDeliveryAddr(item)"
                        is-link
                        center
                        :title="item.mobile"
                        :label="item.region + item.address"
                        icon="location-o"
                    />
                </van-cell-group>

                <!-- 右侧删除按钮 -->
                <template #right>
                    <div class="cart-swipe-right">
                        <van-button @click="deleteDeliveryAddress(item)" class="button delete-button">删除</van-button>
                    </div>
                </template>
            </van-swipe-cell>
        </div>

        <!-- 购物车空状态 -->
        <div class="blank" v-else>
            <van-image :src="blankImage" class="image" />
            <span class="text">您还没有收货地址哟</span>
        </div>

        <div class="add-btn">
            <van-button
                icon="plus"
                block
                round
                color="#27ba9b"
                @click="showAddDeliveryAddr"
            >新增地址</van-button>
        </div>

        <!-- 新增、编辑地址弹层 -->
        <van-popup
            v-model:show="showPopup"
            position="bottom"
            background-color="#fff"
        >
            <div class="address-panel">
                <!-- 关闭按钮 -->
                <span class="close iconfont icon-guanbi" @click="closePopup"></span>
                
                <!-- 标题 -->
                <div class="title">{{ title }}</div>
        
                <van-form @submit="confirmDeliveryAddr">
                    <!-- 收货人 -->
                    <van-field
                        v-model="formData.name"
                        :label-width="labelWidth"
                        name="收货人"
                        label="收货人"
                        left-icon="contact"
                        placeholder="请输入收货人"
                        :rules="[{ required: true, message: '请输入收货人' }]"
                    />
                
                    <!-- 手机号 -->
                    <van-field
                        v-model="formData.mobile"
                        :label-width="labelWidth"
                        type="number"
                        name="手机号"
                        label="手机号"
                        placeholder="请输入手机号"
                        left-icon="phone-o"
                        maxlength="11"
                        :rules="[
                            { required: true, message: '请输入手机号' },
                            { validator, message: '请输入正确格式的手机号' }
                        ]"
                    />

                    <!-- 是否默认 -->
                    <van-field
                        name="是否默认"
                        left-icon="certificate"
                        :label-width="labelWidth"
                        label="是否默认">
                        <template #input>
                            <van-radio-group v-model="formData.is_default" direction="horizontal">
                                <van-radio name="1">是</van-radio>
                                <van-radio name="0">否</van-radio>
                            </van-radio-group>
                        </template>
                    </van-field>

                    <!-- 地区 -->
                    <van-field
                        v-model="formData.region"
                        :label-width="labelWidth"
                        is-link
                        readonly
                        label="所在地区"
                        left-icon="location-o"
                        placeholder="请选择所在地区"
                        @click="show = true"
                        :rules="[
                            { required: true, message: '请选择所在地区' }
                        ]"
                    />

                    <!-- 地区弹层 -->
                    <van-popup v-model:show="show" round position="bottom">
                        <van-cascader
                            v-model="cascaderValue"
                            title="请选择所在地区"
                            :options="areaList"
                            @close="show = false"
                            @change="changeArea"
                            @finish="onFinish"
                        />
                    </van-popup>

                    <!-- 详细地址 -->
                    <van-field
                        v-model="formData.address"
                        left-icon="notes-o"
                        rows="2"
                        autosize
                        label="详细地址"
                        :label-width="labelWidth"
                        type="textarea"
                        maxlength="50"
                        placeholder="请输入详细地址"
                        show-word-limit
                        :rules="[
                            { required: true, message: '请输入详细地址' }
                        ]"
                    />

                    <!-- 按钮 -->
                    <div style="margin: 16px">
                        <van-button
                            type="primary"
                            native-type="submit"
                            round
                            block
                            color="#27BA9B"
                        >
                            保&nbsp;&nbsp;存
                        </van-button>
                    </div>
                </van-form>
            </div>
        </van-popup>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue"
import {reqAddUserDeliveryAddrAPI, reqDeleteUserDeliveryAddrAPI, reqEditUserDeliveryAddrAPI, reqUserDeliveryAddrListAPI} from '@/apis/userDeliveryAddr'
import {reqRegionListAPI} from '@/apis/region'
import { useUserStore } from "@/store/modules/user"
import blankImage from '@/assets/images/blank.png'
import { showConfirmDialog, showSuccessToast } from "vant"

// 用户存储
const userStore = useUserStore()





// ----------------------------- 收货地址列表功能开始 -----------------------------
// 是否显示骨架屏
const isShowSkeleton = ref(false)

// 定义用户收货地址数据
const userDeliveryAddrList = ref([])

onMounted(async () => {
    isShowSkeleton.value = true
	await getUserDeliveryAddrList()
    isShowSkeleton.value = false
})

// 获取用户收货地址
const getUserDeliveryAddrList = async () => {
	const result = await reqUserDeliveryAddrListAPI({status: 1})
  	userDeliveryAddrList.value = result.data.user_delivery_addrs != null ? result.data.user_delivery_addrs : []
}
// ----------------------------- 收货地址列表功能结束 -----------------------------





// ----------------------------- 新增收货地址功能开始 -----------------------------

// 新增、编辑收货地址公共数据
const showPopup = ref()
const title = ref('新增收货地址')
const opt = ref('add')
const labelWidth = ref(60)
const show = ref(false)
const cascaderValue = ref('')
// 验证手机号
const validator = (value) => /^1[3|5|7|8|9]\d{9}$/.test(value)

// 显示新增收货地址
const showAddDeliveryAddr = async () => {
	opt.value = 'add'
	
	// 重置表单
	formData.id = 0
	formData.name = ''
	formData.mobile = ''
	formData.is_default = "0"
	formData.province_id = 0
	formData.city_id = 0
	formData.district_id = 0
	formData.region = ''
	formData.address = ''
	
	// 获取省份数据
	await getProvinceList()

    // 显示弹层
	showPopup.value = true
}

// ----------------------------- 新增收货地址功能结束 -----------------------------





// ----------------------------- 编辑收货地址功能开始 -----------------------------

// 地区数据
const areaList = ref([])

// 提交数据
const formData = reactive({
	id: 0,
	name: '',
	mobile: '',
	province_id: 0,
	city_id: 0,
	district_id: 0,
	region: '',
	address: '',
	is_default: 0
})

// 显示编辑收货地址
const showEditDeliveryAddr = async (item) => {
	opt.value = 'edit'
	// 获取省份数据
	await getProvinceList()

	// 赋值表单
	formData.id = item.id
	formData.name = item.name
	formData.mobile = item.mobile
	formData.is_default = item.is_default + ""
	formData.province_id = item.province_id
	formData.city_id = item.city_id
	formData.district_id = item.district_id
	formData.region = item.region
	formData.address = item.address

	showPopup.value = true
}

// 确认保存收货地址
const confirmDeliveryAddr = async () => {
    let result = null
    if (opt.value == 'add') {
        result = await reqAddUserDeliveryAddrAPI(formData)
    } else {
        result = await reqEditUserDeliveryAddrAPI(formData)
    }
    
    // 判断当前收货地址是否默认,如果默认则需要将其他地址修改为非默认
    if (formData.is_default == 1) {
        userDeliveryAddrList.value.forEach((item) => {
            item.is_default = 0
        })
    }
    
    if (opt.value == 'add') {
        formData.id = result.data.id
        // 必须使用深拷贝，否则点击编辑的时候重新给formData赋值的时候也会修改新增的收货地址
        userDeliveryAddrList.value.unshift(JSON.parse(JSON.stringify(formData)))
        showSuccessToast('新增成功')
    } else {
        // 更新列表数据
        const deliveryAddr = userDeliveryAddrList.value.find((item) => item.id == formData.id)
        for (const key in formData) {
            deliveryAddr[key] = formData[key]
        }
        showSuccessToast('编辑成功')
    }
    

    // 如果是默认地址，添加到 pinia 
    if (formData.is_default == 1) {
        userStore.setDeliveryAddr({
            id: formData.id,
            name: formData.name,
            mobile: formData.mobile,
            province_id: formData.province_id,
            city_id: formData.city_id,
            district_id: formData.district_id,
            region: formData.region,
            address: formData.address,
            is_default: formData.is_default
        })
    }
    
    // 关闭弹层
	showPopup.value = false
}

// 关闭收货地址选择弹层
const closePopup = () => {
    // 显示弹层
	showPopup.value = false
}

// 获取省份数据
const getProvinceList = async () => {
	const result = await reqRegionListAPI({pid: 0})
	const provinceList = result.data.regions != null ? result.data.regions : []
	provinceList.forEach((item) => {
		areaList.value.push({
			value: item.id,
			text: item.name,
            children: []
		})
	})
	
	return 'ok'
}

// 获取地区数据
const getAreaList = async (pid, tabIndex) => {
    console.log(pid, '=', tabIndex);
	const result = await reqRegionListAPI({pid})
	const regions = result.data.regions != null ? result.data.regions : []
    let areas = []
	regions.forEach((item) => {
        if (tabIndex < 1) {
            areas.push({
                value: item.id,
                text: item.name,
                children: []
            })
        } else {
            areas.push({
                value: item.id,
                text: item.name,
            })
        }
	})

    if (tabIndex == 0) {
        areaList.value.find(item => item.value == pid).children = areas
    } else if (tabIndex == 1) {
        areaList.value.forEach((item) => {
            if (item.children.length > 0) {
                if (item.children.find(val => val.value == pid)) {
                    item.children.find(val => val.value == pid).children = areas
                }
            }
        })
    }
}

// 选择地区
const changeArea = ({value,tabIndex}) => {
	getAreaList(value, tabIndex)
}


const onFinish = ({ selectedOptions }) => {
    formData.region = selectedOptions.map((option) => option.text).join('-')
    formData.province_id = selectedOptions[0].value
    formData.city_id = selectedOptions[1].value
    formData.district_id = selectedOptions[2].value
    show.value = false;
}
// ----------------------------- 编辑收货地址功能结束 -----------------------------





// ----------------------------- 删除收货地址功能开始 ---------------------------
const deleteDeliveryAddress = (item) => {
	showConfirmDialog({
        title:'提示',
        message:'确定要删除该地址吗?'
    }).then(async () => {
        await reqDeleteUserDeliveryAddrAPI({ids: item.id})

        // 从数据中删除
        const index = userDeliveryAddrList.value.findIndex((v) => v.id == item.id)
        userDeliveryAddrList.value.splice(index, 1)

        // 判断当前删除的地址是否为选中的地址，是则需要删除持久化的数据
        const deliveryAddr = userStore.deliveryAddr
        if (item.id == deliveryAddr.id) {
            userStore.clearDeliveryAddr()
        }

        showSuccessToast('删除成功')
	}).catch(() => {})
}
// ----------------------------- 删除收货地址功能结束 ---------------------------
</script>

<style scoped lang="scss">
:deep .van-tabs__wrap {
    position: relative;
    z-index: 100;
    width: 100%;
}
.skeleton-address-list {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 47px;
    width: 100%;
    .skeleton-address-item {
        width: 100%;
        padding: 10px;
        margin-top: 10px;
        border-radius: 5px;
        background-color: #fff;
        .skeleton-address-text {
            height: 20px;margin-bottom: 10px;
        }
    }
}

.address-container {
    height: 100vh;
    background: ghostwhite;
    .address-list {
        padding-top: 60px;
    }

    // 空状态
    .blank {
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        height: 60vh;
        .image {
            width: 200px;
            height: 140px;
        }
        .text {
            color: #444;
            font-size: 13px;
            margin: 10px 0;
        }
    }
    .add-btn {
        padding: 10px;
        position: fixed;
        left: 0;
        right: 0;
        bottom: 0;
    }

    .address-panel {
        padding: 0 15px;
        border-radius: 5px 5px 0 0;
        position: relative;
        background-color: #fff;
        .close {
            position: absolute;
            right: 12px;
            top: 12px;
            font-size: 25px;
            color: #27BA9B;
        }
        .title {
            line-height: 1;
            padding: 20px 0;
            text-align: center;
            font-size: 20px;
            font-weight: normal;
            font-weight: bold;
            border-bottom: 1px solid #ddd;
            color: #444;
        }
    }
}

.cart-swipe-right {
    display: flex;
    height: 100%;

    .button {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 50px;
        padding: 6px;
        line-height: 1.5;
        color: #fff;
        font-size: 13px;
    }

    .delete-button {
        background-color: #cf4444;
    }
}

.delete-button {
  height: 100%;
}
</style>